package com.aidex.biz.utils.hengchang;
import com.aidex.biz.service.impl.AccountLogServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.*;
public class CryptDESUtil {

    public static final String ALGORITHM = "DES";
    private static final Logger log = LoggerFactory.getLogger(CryptDESUtil.class);
    /**
     * 第一步：生成DES钥匙
     * @return
     * @throws Exception
     */
    public static String createDesKey() throws Exception {
        // 生成钥匙（根据算法类型生成一个不可逆的算法秘钥）
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(new SecureRandom());
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyEncodedBytes = secretKey.getEncoded();
        String keyBase64 = Base64Util.encryptBASE(keyEncodedBytes);
        log.info("CryptDESUtil##createDesKey：生成DES钥匙的长度是：【{}】，具体内容是：【{}】",keyEncodedBytes.length, keyBase64);
        return keyBase64;
    }

    /**
     * 第二步：DES加密
     *      利用DES钥匙，对信息加密
     * @return
     */
    public static String desEntrypt(String keyBase64, String context) throws Exception {
        log.info("CryptDESUtil##desEntrypt：DES钥匙是：【{}】，待加密内容是：【{}】",keyBase64, context);
        byte[] inputDataBytes = context.getBytes();
        // 生成密钥（根据不可逆的钥匙生成秘钥）
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey sk = keyFactory.generateSecret(new DESKeySpec(Base64Util.decryptBASE(keyBase64)));
        // 生成cipher对象：指定算法
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        // 初始化cipher，加密
        cipher.init(Cipher.ENCRYPT_MODE, sk);
        byte[] out = cipher.doFinal(inputDataBytes);
        String outString = Base64Util.encryptBASE(out);
        log.info("CryptDESUtil##desEntrypt：DES加密后的内容是：【{}】",outString);
        return outString;
    }
    /**
     *  第三步：DES 解密
     *      根据DES钥匙，对DES密文解密
     * @param keyBase64
     * @param outStr
     * @return
     * @throws Exception
     */
    public static String desDecrypt(String keyBase64, String outStr) throws Exception {

        byte[] out = Base64Util.decryptBASE(outStr);
        // 生成密钥（根据不可逆的钥匙生成秘钥）
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey sk = keyFactory.generateSecret(new DESKeySpec(Base64Util.decryptBASE(keyBase64)));
        // 生成cipher对象：指定算法
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        // 初始化cipher，解密
        cipher.init(Cipher.DECRYPT_MODE, sk);
        byte[] outData = cipher.doFinal(out);
        String outputStr = new String(outData);
        log.info("CryptDESUtil##desEntrypt：DES解密后的内容是：【{}】",outputStr);
        return outputStr;
    }
}
